package com.lai.shop.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.cloud.context.utils.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.lai.shop.constant.CommonConstant;
import com.lai.shop.dao.OrderItemDao;
import com.lai.shop.dao.UserDao;
import com.lai.shop.dao.UserReceiveAddressDao;
import com.lai.shop.entity.OrderItemEntity;
import com.lai.shop.entity.UserEntity;
import com.lai.shop.entity.UserReceiveAddressEntity;
import com.lai.shop.exception.BizException;
import com.lai.shop.interceptor.CartInterceptor;
import com.lai.shop.interceptor.OrderInterceptor;
import com.lai.shop.service.CartService;
import com.lai.shop.service.OrderItemService;
import com.lai.shop.service.UserReceiveAddressService;
import com.lai.shop.utils.PageUtils;
import com.lai.shop.utils.Query;
import com.lai.shop.vo.CartItemVo;
import com.lai.shop.vo.CartVo;
import com.lai.shop.vo.OrderDetailVo;
import com.lai.shop.vo.OrderSubmitVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.lai.shop.dao.OrderDao;
import com.lai.shop.entity.OrderEntity;
import com.lai.shop.service.OrderService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    UserReceiveAddressDao userReceiveAddressDao;

    @Autowired
    ThreadPoolExecutor executors;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    CartService cartService;

    @Autowired
    OrderItemDao orderItemDao;



    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        String confirmStatus = (String) params.get("confirmStatus");
        String deleteStatus = (String) params.get("deleteStatus");
        String status = (String) params.get("status");
        QueryWrapper<OrderEntity> queryWrapper = new QueryWrapper<>();

        if (!StringUtils.isEmpty(key)) {
            queryWrapper.eq("id", key)
                    .or().eq("user_id", key)
                    .or().like("user_username", key)
                    .or().eq("order_sn", key);
        }

        if (!StringUtils.isEmpty(confirmStatus)) {
            queryWrapper.eq("confirm_status", confirmStatus);
        }

        if (!StringUtils.isEmpty(deleteStatus)) {
            queryWrapper.eq("delete_status", deleteStatus);
        }

        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("status", status);
        }

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public OrderDetailVo submitOrder(HttpSession session) {
        OrderDetailVo orderSubmitVo = new OrderDetailVo();
        //1、获取用户全部收货地址
        //UserEntity userEntity = OrderInterceptor.threadLocal.get();
        Object user = session.getAttribute(CommonConstant.LOGIN_USER);
        if (ObjectUtil.isNotNull(user) && user instanceof UserEntity) {
            List<UserReceiveAddressEntity> addressList = userReceiveAddressDao.selectList(new QueryWrapper<UserReceiveAddressEntity>()
                    .eq("user_id", ((UserEntity) user).getId()));
            orderSubmitVo.setUserReceiveAddressEntityList(addressList);

            //获取用户购物车的所有选中项  并  获取最新价格
            CartVo cartVo = cartService.getCheckCartAndNewPrice(((UserEntity) user).getId());
            orderSubmitVo.setCartVo(cartVo);

            return orderSubmitVo;
        } else {
            throw new BizException("请先登录");
        }

    }


    @Transactional(rollbackFor = {BizException.class, Exception.class})
    @Override
    public void saveOrder(OrderSubmitVo orderSubmitVo, HttpSession session) {
        //1、获取用户的默认地址
        Object userEntity = session.getAttribute(CommonConstant.LOGIN_USER);
        if (ObjectUtil.isNotNull(userEntity) && userEntity instanceof UserEntity) {
            UserEntity user = (UserEntity) userEntity;
            UserReceiveAddressEntity defaultAddress = userReceiveAddressDao.selectOne(new QueryWrapper<UserReceiveAddressEntity>().
                    eq("user_id", user.getId()).and(wrapper -> {
                wrapper.eq("default_status", CommonConstant.TRUE);
            }));
            //2、保存订单
            CartVo cartVo = cartService.getCartByUserId(user.getId());
            //生成订单号
            String orderSn = IdWorker.getTimeId();
            OrderEntity orderEntity = OrderEntity.builder()
                    .userId(user.getId())
                    .userUsername(user.getUsername() != null ? user.getUsername() : user.getNickname())
                    .orderSn(orderSn)
                    .totalAmount(cartVo.getTotalAmount())
                    .payType(orderSubmitVo.getPayType())
                    .status(CommonConstant.FALSE)
                    .receiverName(defaultAddress.getName())
                    .receiverProvince(defaultAddress.getProvince())
                    .receiverPhone(defaultAddress.getPhone())
                    .receiverCity(defaultAddress.getCity())
                    .receiverRegion(defaultAddress.getRegion())
                    .receiverDetailAddress(defaultAddress.getDetailAddress())
                    .greetingMessage(orderSubmitVo.getGreetingMessage())
                    .note(orderSubmitVo.getNote())
                    .confirmStatus(CommonConstant.FALSE)
                    .deleteStatus(CommonConstant.FALSE)
                    .paymentTime(DateUtil.parse(orderSubmitVo.getDeliveryTime()))
                    .build();
            baseMapper.insert(orderEntity);
            //3、减少库存
            List<CartItemVo> items = cartVo.getItems();

            List<CartItemVo> cartItemVos = items.stream().filter(CartItemVo::getIsCheck).collect(Collectors.toList());
            //Map<Long, Integer> collect = items.stream().filter(CartItemVo::getIsCheck).collect(Collectors.toMap(CartItemVo::getProductId, CartItemVo::getCount));


            for (CartItemVo item : cartItemVos) {
                userReceiveAddressDao.subStock(item.getProductId(),item.getCount());
            }



            //4、保存订单项


            for (CartItemVo item : cartItemVos) {
                OrderItemEntity orderItemEntity = new OrderItemEntity();
                //TODO 订单号
                //orderItemEntity.setOrderId();
                orderItemEntity.setOrderSn(orderSn);
                //TODO
                //orderItemEntity.setCategoryId();
                orderItemEntity.setProductId(item.getProductId());
                orderItemEntity.setProductName(item.getProductName());
                orderItemEntity.setProductPic(item.getPicture());
                orderItemEntity.setProductPrice(item.getPrice());
                orderItemEntity.setProductAmount(item.getCount());
                orderItemDao.insert(orderItemEntity);
            }
        }
    }

}
